<?php

class User {
	
	public $id;
	public $ime;
	public $imeTima;
	private $sifra;
	
	
	// constructor
	
	public function __construct($i = 0) {
		$this->id = $i;
		if ($i != 0) {
			$n = $this->getfromdb($i);
			$this->ime = $n['ime'];
			$this->imeTima = $n['imeTima'];
		}
	}
	
	// functions
	
	private function getfromdb($number) {
		$q = "SELECT ime, imeTima FROM `user` WHERE id = " . $number;
		$r = mysql_query("set names 'utf8'");
		$r = mysql_query($q);
		if (!mysql_num_rows($r)) throw new Exception("Ne postoji User za zadati ID!");
		return (mysql_fetch_array($r));
	}
	

	// admin
	
	public function setSifra($s) {
		$this->sifra = $s;
	}
	
	public function userExists() {
		$q = "SELECT id FROM `user` WHERE `ime` = '" . $this->ime ."'";
		$r = mysql_query("set names 'utf8'");
		$r = mysql_query($q);
		if (mysql_num_rows($r)) return true;
		else return false;
	}
	
	public function insertIntoDb() {
		$username = $this->ime;
		$password = $this->sifra;
		
		// Create a 256 bit (64 characters) long random salt
		// Let's add 'something random' and the username
		// to the salt as well for added security
		$salt = hash('sha256', uniqid(mt_rand(), true) . 'miigramokosarku' . strtolower($username));
		
		// Prefix the password with the salt
		$hash = $salt . $password;
		
		// Hash the salted password a bunch of times
		for ( $i = 0; $i < 100000; $i ++ ) {
		  $hash = hash('sha256', $hash);
		}
		
		// Prefix the hash with the salt so we can find it back later
		$hash = $salt . $hash;
	
		$q = "INSERT INTO user (ime, imeTima, sifra) VALUES ('".$this->ime."', '".$this->imeTima."', '".$hash."')";
		$r = mysql_query("set names 'utf8'");
		if (mysql_query($q)) {
			// echo "Uspesno ste se registrovali.";
		}
	}
	
	public function logIn($u, $p) {
		$q = "SELECT id, sifra FROM user WHERE ime = '" . $u ."'";
		$r = mysql_query("set names 'utf8'");
		$r = mysql_query($q);
		if (!mysql_num_rows($r)) return ("user");
		$n = mysql_fetch_array($r);
		
		// The first 64 characters of the hash is the salt
		$salt = substr($n['sifra'], 0, 64);
		
		$hash = $salt . $p;
		
		// Hash the password as we did before
		for ( $i = 0; $i < 100000; $i ++ ) {
		  $hash = hash('sha256', $hash);
		}
		
		$hash = $salt . $hash;
				
		if ( $hash == $n['sifra'] ) {
			$_SESSION['bl_user_id'] = $n['id'];
			return true;
		}
			else return "pass";
	}
	
	public function getNewUserID() {
		$q = "SELECT id FROM user ORDER BY id DESC LIMIT 1";
		$r = mysql_query("set names 'utf8'");
		$r = mysql_query($q);
		if (!mysql_num_rows($r)) throw new Exception("No users in database!");
		$n = mysql_fetch_array($r);
		return $n['id'];
	}
	
} // end of class User


?>